﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Winform跨线程访问报错问题解决
{
    public class ThreadMethodHelper
    {
        Form form;

        public ThreadMethodHelper(Form form)
        {
            this.form = form;
        }

        delegate void SetTextCallBack(String text, TextBox textBox);
        delegate String GetTextCallBack(TextBox textBox);

        public void SetText(String text, TextBox textBox)
        {
            //判断控件是否是在创建控件的线程中调用此控件
            if (textBox.InvokeRequired)
            {
                SetTextCallBack d = new SetTextCallBack(SetText);
                form.Invoke(d, text, textBox);
            }
            else
            {
                textBox.Text = text;
            }
        }

        public String GetText(TextBox textBox)
        {
            if (textBox.InvokeRequired)
            {
                GetTextCallBack d = new GetTextCallBack(GetText);
                return (String)form.Invoke(d, new object[] { textBox });
            }
            else
            {
                return textBox.Text;
            }
        }



    }
}
